package com.dongdongshop.shiro;

import com.dongdongshop.utils.JwtUtil;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroRealm realm() {
        ShiroRealm petRealm = new ShiroRealm();
        petRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return petRealm;
    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(realm());
        return manager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        LinkedHashMap<String,String> map = new LinkedHashMap<>();
        map.put("/login", DefaultFilter.anon.name());
        map.put("/seller/login", DefaultFilter.anon.name());
        map.put("/loginOut", DefaultFilter.logout.name());
        map.put("/**", DefaultFilter.authc.name());

        map.put("/delete",DefaultFilter.perms.name());
        shiroFilterFactoryBean.setLoginUrl("/ToLogin");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        LogoutFilter logoutFilter = new LogoutFilter();
        logoutFilter.setRedirectUrl("/ToLogin");
        Map<String, Filter> filter = new LinkedHashMap<>();
        filter.put("logout", logoutFilter);
        shiroFilterFactoryBean.setFilters(filter);

        return shiroFilterFactoryBean;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(7);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }

    @Bean
    public JwtUtil createjwtUtil(){
        return new JwtUtil();
    }
}
